import React, { Component } from 'react';
import { ajax, base, createPage, toast, getMultiLang,DongbaToLocalTime } from 'nc-lightapp-front';
import Referloader from '../../../ReferLoader';
import FirstTable from './firstTable'; //第一个表格
import SecondTable from './secondTable'; //第二个表格
import ThirdContions from './thirdContions'; //第三部组件
import { getDefaultBusinessDate } from '../../businessDate';
import { buttonClick, initTemplate } from '../events/index';
import promptbox from '../../promptbox';
import getInitOrg from '../../pubUtils/getInitOrg';
import './index.less';
import moment from 'moment'; 
const { NCFormControl, NCRow, NCCol, NCDatePicker, NCStep,NCTZDatePickClientTime } = base;
const NCSteps = NCStep.NCSteps;
const format = 'YYYY-MM-DD';
const urls = {
	oncalculation: '/nccloud/arap/agiotage/oncalculation.do',
	onconfirm: '/nccloud/arap/agiotage/onconfirm.do'
};
const defaultProps12 = {
	prefixCls: 'bee-table',
	multiSelect: {
		type: 'checkbox',
		param: 'key'
	}
};
let isGoCancelPro = false; //是否继续进行取消损益
let isSelectedData = false; //是否选中行数据
let businessDates, businessDatesH, Hms;
let transData;

function getHMS() {
	var date = new Date();
	var seperator2 = ':';
	var hour = date.getHours();
	var minutes = date.getMinutes();
	var seconds = date.getSeconds();
	if (hour >= 0 && hour <= 9) {
		hour = '0' + hour;
	}
	if (minutes >= 0 && minutes <= 9) {
		minutes = '0' + minutes;
	}
	if (seconds >= 0 && seconds <= 9) {
		seconds = '0' + seconds;
	}
	var currentdate = ' ' + hour + seperator2 + minutes + seperator2 + seconds;
	return currentdate;
}

class FirstCalculation extends Component {
	constructor(props) {
		super(props);
		this.state = {
			tableData: [], //第一个表格数据
			selectedDatas: [], //选中行的数据
			isFirstTableShow: true, //是否显示第一步表格
			isFristBtnsShow: true, //是否显示第一步的按钮
			isKeepShow: true, //是否显示保存按钮
			isBottomShow: true,
			current: 0,
			steps: [],
			mainData: {
				date: { display: null, value: null }, //计算日期
				pk_org: {
					display: null,
					value: null
				} //财务组织
			},
			json: {}
		};
		this.handleReturn = this.handleReturn.bind(this);
	}
	componentWillMount() {
		let { mainData } = this.state;
		initTemplate.call(this, this.props);
		let callback = (json) => {
			this.setState({ json: json }, () => {
				this.setState({
					steps: [
						{
							title: this.state.json['public-000085'] /* 国际化处理： 选择币种*/
						},
						{
							title: this.state.json['public-000086'] /* 国际化处理： 损益试算结果*/
						},
						{
							title: this.state.json['public-000087'] /* 国际化处理： 完成汇兑损益*/
						}
					]
				});
				setTimeout(() => {
					getDefaultBusinessDate().then((businessDate) => {
						if (businessDate) {
							businessDatesH = businessDate.businessDate;
							businessDates = businessDatesH.substring(0, 10);
							mainData.date = {
								display: businessDates,
								value: businessDatesH
							};
							this.setState({
								mainData
							});
						}
					});
				}, 0);
			});
		};
		getMultiLang({ moduleId: 'public', domainName: 'arap', currentLocale: 'simpchn', callback });
	}
	componentDidMount() {
		Hms = getHMS();
		let { mainData } = this.state;
		let PK_org = this.props.getUrlParam('Pk_org')
			? JSON.parse(this.props.getUrlParam('Pk_org'))
			: { display: null, value: null };
		mainData.pk_org.value = PK_org.value;
		mainData.pk_org.display = PK_org.display;
		mainData.pk_org.refpk2 = PK_org.refpk2;
		this.setState({
			mainData
		});
		this.props.button.setButtonVisible([ 'Pre', 'Save' ], false);
		if (PK_org.value) {
			this.getTableData();
		}
		let appcode = this.props.getSearchParam('c');
		if (!PK_org.value) {
			getInitOrg(appcode, this.cb);
		}
	}

	cb = (pkOrg) => {
		let { mainData } = this.state;
		mainData.pk_org = {
			display: pkOrg.display,
			value: pkOrg.value,
			refpk2: pkOrg.refpk2
		};
		this.setState(
			{
				mainData
			},
			() => {
				this.getTableData();
			}
		);
	};

	//获取第一步表格数据
	getTableData = () => {
		let { mainData } = this.state;
		let initdata = {
			date: mainData.date.value,
			sfbz: this.props.sfbz,
			pk_org: mainData.pk_org.value
		};
		ajax({
			url: '/nccloud/arap/agiotage/initpanel.do',
			data: initdata,
			success: (res) => {
				let { success, data } = res;
				if (success) {
					data.map((item, i) => {
						item.key = i;
					});
					this.child1.setFirstTableDatas(data);
					this.setState({
						tableData: data
					});
				}
			}
		});
	};

	//获取选中行的数据
	getSelectedDatas = (datas) => {
		this.setState(
			{
				selectedDatas: datas
			},
			() => {}
		);
	};

	//是否进行取消损益
	handleGoCancelPro = () => {
		let { selectedDatas } = this.state;
		if (selectedDatas.length == 0) {
			isGoCancelPro = false;
			isSelectedData = false;
		} else {
			isSelectedData = true;
			for (var i = 0, len = selectedDatas.length; i < len; i++) {
				if (selectedDatas[i].hasOwnProperty('jssj')) {
					isGoCancelPro = true;
					break;
				}
			}
		}
	};

	//上一步
	handleBack = () => {
		const current = this.state.current - 1;
		let { tableData } = this.state;
		this.setState(
			{
				isFirstTableShow: true,
				isFristBtnsShow: true,
				current
			},
			() => {
				this.child1.setFirstTableDatas(tableData);
				this.props.button.setButtonVisible([ 'Next', 'CancelProfit' ], true);
				this.props.button.setButtonVisible([ 'Pre', 'Save' ], false);
			}
		);
	};

	//获取第二步的表格数据
	getSecTableData = (url, transData) => {
		let agiotageBzVOsData = transData.agiotageBzVOs;
		let arr = [];
		let obj = {};
		for (let i = 0, len = agiotageBzVOsData.length; i < len; i++) {
			obj = {
				m_sBzbm: agiotageBzVOsData[i].bzbm,
				m_sBzmc: agiotageBzVOsData[i].bzmc,
				lastCalDate: agiotageBzVOsData[i].jssj ? agiotageBzVOsData[i].jssj : null
			};
			arr.push(obj);
		}
		let oncaldata = {
			agiotageBzVOs: arr,
			date: transData.queryData.date.value,
			sfbz: this.props.sfbz,
			pk_org: transData.queryData.pk_org.value
		};
		ajax({
			url: url,
			data: oncaldata,
			success: (res) => {
				//此处使用箭头函数，如果不使用箭头函数，一定要bind(this)
				let { success, data } = res;
				if (success) {
					if (url == '/nccloud/arap/agiotage/oncalculation.do') {
						let showData = data.showData;
						if (showData.length > 0) {
							var current = this.state.current + 1;
							this.setState(
								{
									isFirstTableShow: false,
									isFristBtnsShow: false,
									isKeepShow: true,
									current
								},
								() => {
									this.child.getMultilingual(showData, data, transData);
									this.props.button.setButtonVisible([ 'Next', 'CancelProfit' ], false);
									this.props.button.setButtonVisible([ 'Pre', 'Save' ], true);
								}
							);
						} else {
							if (data.error) {
								toast({
									duration: 3, // 消失时间，默认是3秒; 值为 infinity 时不消失,非必输
									color: 'danger', // 提示类别，默认是 "success",非必输
									content: data.error // 提示内容,非必输
								});
							}
						}
					} else {
						var current = this.state.current + 1;
						this.setState(
							{
								isKeepShow: !this.state.isKeepShow,
								current,
								isBottomShow: !this.state.isBottomShow
							},
							() => {
								this.props.button.setButtonVisible([ 'Next', 'CancelProfit' ], false);
								this.props.button.setButtonVisible([ 'Pre', 'Save' ], false);
							}
						);
						toast({
							color: 'success',
							content: this.state.json['public-000088'] /* 国际化处理： 损益成功*/
						});
					}
				} else {
					if (data.error) {
						toast({
							duration: 3, // 消失时间，默认是3秒; 值为 infinity 时不消失,非必输
							color: 'danger', // 提示类别，默认是 "success",非必输
							content: data.error // 提示内容,非必输
						});
					}
				}
			}
		});
	};

	//下一步
	handleNext = () => {
		let { mainData, selectedDatas } = this.state;
		this.state.tableData = this.child1.getFirstTableDatas();
		transData = {
			agiotageBzVOs: [],
			queryData: mainData
		};
		if (selectedDatas.length == 0) {
			toast({
				color: 'warning',
				content: this.state.json['public-000041'] /* 国际化处理： 请至少选择一行数据！*/
			});
			return;
		} else {
			for (let i = 0, len = selectedDatas.length; i < len; i++) {
				transData.agiotageBzVOs.push(selectedDatas[i]);
			}
		}
		if (mainData.pk_org.value && mainData.date.display) {
			this.getSecTableData(urls['oncalculation'], transData);
		} else {
			if (!mainData.pk_org.value) {
				toast({
					color: 'warning',
					content: this.state.json['public-000089'] /* 国际化处理： 请先选择财务组织！*/
				});
				return;
			}
			toast({
				color: 'warning',
				content: this.state.json['public-000146'] /* 国际化处理： 请先选择计算日期！*/
			});
			return;
		}
	};

	//取消损益
	handleCancelProfit = () => {
		let { selectedDatas } = this.state;
		let len = selectedDatas.length;
		this.handleGoCancelPro();
		if (len == 0 || (len > 0 && !isSelectedData)) {
			toast({
				color: 'warning',
				content: this.state.json['public-000090'] /* 国际化处理： 请选择已经计提汇兑损益后的币种进行取消操作！*/
			});
		} else {
			if (isGoCancelPro) {
				promptbox(
					this.state.json['public-000091'],
					this.callBackOK,
					'warning'
				); /* 国际化处理： 同一批次的汇兑损益记录都将被取消，是否继续？*/
			} else {
				toast({
					color: 'warning',
					content: this.state.json['public-000090'] /* 国际化处理： 请选择已经计提汇兑损益后的币种进行取消操作！*/
				});
			}
		}
	};
	//取消损益发送ajax事件
	callBackOK = () => {
		let { mainData, selectedDatas } = this.state;
		let agiotageMainVOss = [];
		if (selectedDatas.length > 0) {
			for (var i = 0, len = selectedDatas.length; i < len; i++) {
				if (selectedDatas[i].hasOwnProperty('jssj')) {
					agiotageMainVOss.push({
						dealno: selectedDatas[i].clbh,
						busidate: selectedDatas[i].jssj
					});
				}
			}
		}
		let cancelsumdata = {
			agiotageMainVOs: agiotageMainVOss,
			date: mainData.date.value,
			sfbz: this.props.sfbz,
			pk_org: mainData.pk_org.value
		};
		ajax({
			url: '/nccloud/arap/agiotage/onCancelAgiotageBySum.do',
			data: cancelsumdata,
			success: (res) => {
				let { success } = res;
				if (success) {
					toast({
						color: 'success',
						content: this.state.json['public-000092'] /* 国际化处理： 取消损益成功！*/
					});
					this.child1.changAllCheckBoxStatus();
					this.getTableData();
					this.setState({
						selectedDatas: []
					});
				}
			},
			error: (msg) => {
				msg = msg.message.substring(6);
				toast({
					color: 'danger',
					content: msg
				});
			}
		});
	};

	//损益记录
	handleProfitRecord = () => {
		let { mainData } = this.state;
		this.props.linkTo(this.props.url, {
			Pk_org: JSON.stringify(mainData.pk_org),
			pagecode: this.props.pagecode
		});
	};

	//保存
	handleKeep = () => {
		this.getSecTableData(urls['onconfirm'], transData);
	};

	//返回第一步
	handleReturn = () => {
		this.setState(
			{
				current: 0,
				isBottomShow: true
			},
			() => {
				this.getTableData();
				this.props.button.setButtonVisible([ 'Next', 'CancelProfit' ], true);
				this.props.button.setButtonVisible([ 'Pre', 'Save' ], false);
			}
		);
	};

	//参照展示
	getRefer = (tag, refcode, key, mainData) => {
		return (
			<div className="finance">
				<div className="finance-refer">
					<Referloader
						fieldid = "FinanceOrgTreeRef"
						tag={tag}
						refcode={refcode}
						value={{
							refname: key.display,
							refpk: key.value,
							refpk2: key.refpk2
						}}
						onChange={(v) => {
							key.value = v.refpk;
							key.refpk2 = v.refpk2;
							key.display = v.refname;
							this.setState(
								{
									mainData
								},
								() => {
									if (mainData.pk_org.value == null) {
										toast({
											color: 'warning',
											content: this.state.json['public-000093'] /* 国际化处理： 财务组织为空，请重新选择！*/
										});
									} else {
										this.getTableData();
									}
								}
							);
						}}
						queryCondition={() => {
							if (tag == 'FinanceOrgTreeRef') {
								return {
									AppCode: this.props.getSearchParam('c'),
									DataPowerOperationCode: 'fi', //使用权组
									isDataPowerEnable: 'Y',
									TreeRefActionExt: 'nccloud.web.refer.sqlbuilder.PrimaryOrgSQLBuilder'
								};
							}
						}}
					/>
				</div>
			</div>
		);
	};

	//input展示
	getInput = (name, key) => {
		return (
			<div className="finance">
				<span className="lable">{name}</span>
				<div className="finance-refer">
					<NCFormControl fieldid={'input'+key} value={DongbaToLocalTime(moment(key.display)).format(format)} />
				</div>
			</div>
		);
	};

	//input财务组织展示
	getInputRefer = (name, key) => {
		return (
			<div className="finance">
				<span className="lable">{name}</span>
				<div className="finance-refer">
					<NCFormControl fieldid="showorg" value={key.display} />
				</div>
			</div>
		);
	};

	//第一步的查询条件
	getQueryCons = (mainData) => {
		let { pk_org, date } = mainData;
		return (
			<div className="query-cons">
				<div className="query-cons-input">
					{this.getRefer('FinanceOrgTreeRef', 'uapbd/refer/org/FinanceOrgTreeRef/index.js', pk_org, mainData)}
				</div>
				<div className="query-cons-input">
					<NCTZDatePickClientTime
                        fieldid="datepicker"
						format={format}
						showStar
						onChange={(d) => {
							date.value = d + Hms;
							date.display = d;
							this.setState(
								{
									mainData
								},
								() => {
								}
							);
						}}
						value={date.display}
					/>
				</div>
			</div>
		);
	};

	//第二步的查询条件
	getSecQueryCons = (mainData) => {
		let { pk_org, date } = mainData;

		return (
			<div className="query-cons">
				<div className="query-cons-input">{this.getInputRefer('', pk_org)}</div>
				<div className="query-cons-input">{this.getInput('', date)}</div>
			</div>
		);
	};

	//第一步的内容
	getFirstContent = () => {
		let { tableData } = this.state;
		return (
			<div>
				<FirstTable
					json={this.state.json}
					getSelectedDatas={this.getSelectedDatas.bind(this)}
					onRef1={(ref) => {
						this.child1 = ref;
					}}
				/>
			</div>
		);
	};

	//第二步的内容
	getSecondContent = () => {
		return (
			<div>
				<SecondTable
					onRef={(ref) => {
						this.child = ref;
					}}
					sfbz={this.props.sfbz}
				/>
			</div>
		);
	};

	//第三部的内容
	getThirdContent = () => {
		let { mainData } = this.state;
		let { date, pk_org } = mainData;
		return <ThirdContions date={date} pkOrg={pk_org} handleReturn={this.handleReturn} jsonlang={this.state} />;
	};

	returnDescription = (current, index) => {
		if (index == current) {
			if (index == 2) {
				return this.state.json['public-000094']; /* 国际化处理： 已完成*/
			}
			return this.state.json['public-000095']; /* 国际化处理： 进行中*/
		} else if (index < current) {
			return this.state.json['public-000094']; /* 国际化处理： 已完成*/
		} else {
			return;
		}
	};

	render() {
		let { current, isBottomShow, mainData, steps } = this.state;
		let { button } = this.props;
		let { createButtonApp } = button;
		return (
			<div id="firstpageId">
				<ul className="account-head">
					<div className="account-head-steps nc-theme-area-bgc">
						<NCRow>
							<NCCol md={6} mdOffset={3} xs={6} xsOffset={3} sm={6} smOffset={3}>
								<div className="step">
									<NCSteps current={current}>
										{steps.map((item, index) => (
											<NCStep
												key={item.title}
												title={item.title}
												description={this.returnDescription(current, index)}
											/>
										))}
									</NCSteps>
								</div>
							</NCCol>
						</NCRow>
					</div>
					<div className="cal-header nc-theme-area-bgc nc-theme-form-label-c nc-theme-area-split-bc">
						<h2 className="title">
							{current == 0 && <span className="titleStar">*</span>}
							{this.state.json['public-000096']}
							{/* 国际化处理： 汇兑损益*/}
						</h2>
						{current == 0 && this.getQueryCons(mainData)}
						{current == 1 && this.getSecQueryCons(mainData)}
						<div className="cal-btn-group">
							{createButtonApp({
								area: 'list_head',
								buttonLimit: 5,
								onButtonClick: buttonClick.bind(this)
							})}
						</div>
					</div>
				</ul>
				<div className="steps-content">
					{current == 0 && this.getFirstContent()}
					{current == 1 && this.getSecondContent()}
					{current == 2 && this.getThirdContent()}
				</div>
				<div className={isBottomShow ? 'account-bottom' : ''}>
					<div />
					<div>
						{createButtonApp({
							area: 'list_bottom',
							buttonLimit: 5,
							onButtonClick: buttonClick.bind(this)
						})}
					</div>
				</div>
			</div>
		);
	}
}

FirstCalculation.defaultProps = defaultProps12;

FirstCalculation = createPage({})(FirstCalculation);

export default FirstCalculation;
